package com.example.foodsy.controller;

import com.example.foodsy.entity.Admin;
import com.example.foodsy.utils.Result;
import com.example.foodsy.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.example.foodsy.utils.JwtUtils;

/**
 * <p>
 * 系统管理员表 前端控制器
 * </p>
 *
 * @author cgc
 * @since 2025-09-23
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtils jwtUtils;
    // 管理员登录
    @PostMapping("/login")
    public Result login(String adminName, String adminPassword) {
        Result result = adminService.getAdminByNameByPass(adminName, adminPassword);
        if (result.getSuccess()) {
            Admin admin = (Admin) result.getData();
            // 生成JWT令牌（角色为ADMIN）
            String token = jwtUtils.generateToken(admin.getAdminId(), "ADMIN");
            return Result.ok(token); // 返回令牌
        }
        return result; // 登录失败
    }


    // 1. 新增管理员
    @PostMapping( "/add")
    @PreAuthorize("hasRole('ADMIN')")
    public Result addAdmin(@RequestBody Admin admin) {
      return adminService.addAdmin(admin);
    }

    // 2. 删除管理员
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result deleteAdmin(@PathVariable Long id) {
        return adminService.deleteAdmin(id);
    }

    // 3. 修改管理员信息
    @PutMapping("/update")
    @PreAuthorize("hasRole('ADMIN')")
    public Result updateAdmin(@RequestBody Admin admin) {
        return adminService.updateAdmin(admin);
    }

    // 4. 根据ID查询管理员
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result getAdminById(@PathVariable Long id) {
       return adminService.getAdminById(id);
    }

    // 5. 查询管理员列表（支持分页）
    @GetMapping("/list")
    @PreAuthorize("hasRole('ADMIN')")
    public Result getAdminList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            // 可选：添加查询条件
            @RequestParam(required = false) String username) {

       return adminService.getAdminList(pageNum, pageSize, username);
    }

}
